/**
 * FileFind - ftp/shares indexing and search php engine
 * Module: webapp-jsf12
 * Description: Implementation of webapp using JSF 1.2
 * Copyright (c) 2003-2010 Rage Steel, www.gt2.ru
 */
package ru.ffind.webapp.jsf21.beans;

import java.text.MessageFormat;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

import ru.ffind.common.model.Directory;
import ru.ffind.common.model.Entry;
import ru.ffind.common.model.Host;
import ru.ffind.common.model.HostPath;
import ru.ffind.common.tools.HostPathParser;
import ru.ffind.persist.service.EntryService;
import ru.ffind.persist.service.HostService;

/**
 * Bean for browsing hosts.
 * 
 * @author Rage Steel
 */
@ManagedBean
public class BrowseBean {
	
	@ManagedProperty("#{hostServiceBean}")
	private HostService hostService;
	
	@ManagedProperty("#{entryServiceBean}")
	private EntryService entryService;

	@ManagedProperty("#{msgs}")
	private ResourceBundle msgs;

	private String path = "";
	
	private HostPath hostPath = HostPath.EMPTY;
	
	private List<? extends Entry> entries;
	
	public void setHostService(HostService hostService) {
		this.hostService = hostService;
	}
	
	public void setEntryService(EntryService entryService) {
		this.entryService = entryService;
	}
	
	public void setMsgs(ResourceBundle msgs) {
		this.msgs = msgs;
	}

	public String getPath() {
		return path;
	}
	
	public void setPath(String path) {
		this.path = path;
	}
	
	public void preRenderView(ComponentSystemEvent event) {
		fillEntries();
	}
	
	public List<? extends Entry> getEntries() {
		return entries;
	}
	
	/**
	 * Return path elements for constructing path string with links
	 * @return
	 */
	public List<Directory> getPathElements() {
		return Collections.emptyList();
	}

	private void fillEntries() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		
		entries = Collections.emptyList();
		hostPath = HostPathParser.parse(path);
		String hostName = hostPath.getHostName();
		Host host = hostService.findByNameOrNull(hostName);
		if (null == host) {
			String summary = formatMessageFromBundle(msgs, "errorHostNotFound", hostName);
			facesContext.addMessage(null, 
					new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null));
			return;
		}
		
		entries = entryService.findEntriesByHostPath(host, hostPath);
	}
	
	private static String formatMessageFromBundle(ResourceBundle msgs, String resourceKey, Object... params) {
		String string = msgs.getString(resourceKey);
		if (0 == params.length) {
			return string;
		} else {
			return MessageFormat.format(string, params);
		}
	}
	
}
